package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * @author Eric
 * @Create 2020-09-16  17:09
 * @Version project-workspace-0912
 **/

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    private TravelGroupDao travelGroupDao;

    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
        //1 新增跟团游，向t_travelgroup中添加数据，新增后返回新增的id
        travelGroupDao.add(travelGroup);
        //2 新增跟团游和自由行中间表t_travelgroup_travelitem新增数据(新增几条，由travelItemIds决定)
        this.setTravelgroupAndTravelitem(travelGroup.getId(),travelItemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用分页插件PageHelper 设置当前页和页面大小
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //响应分页插件的Page对象
        Page<TravelGroup> page = travelGroupDao.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public TravelGroup findById(Integer id) {
        return  travelGroupDao.findById(id);
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }

    @Override
    public List<Integer> findTravelItemIdByTravelgroupId(Integer id) {
        return travelGroupDao.findTravelItemIdByTravelgroupId(id);
    }

    @Override
    public void edit(TravelGroup travelGroup, Integer[] travelItemIds) {
        //更新关联，整体的思路:先删除，再添加

        // 1：修改跟团游的基本信息
        travelGroupDao.edit(travelGroup);
        /**
         *2.更新关联，整体的思路:先删除，再添加
         */
        // 删除之前中间表的数据
        travelGroupDao.deleteTravelGroupAndTravelItemByTravelGroupId(travelGroup.getId());
        // 再新增页面选中的数据
        setTravelgroupAndTravelitem(travelGroup.getId(),travelItemIds);

    }

    public void  setTravelgroupAndTravelitem(Integer travelGroupId,Integer[] travelItemIds){
            //用map封装自由行的所有Id
              if(travelItemIds != null && travelItemIds.length > 0){
                  for (Integer travelItemId : travelItemIds) {
                      HashMap<String,Integer> map = new HashMap<>();
                      map.put("travelGroupId",travelGroupId);
                      map.put("travelItemId",travelItemId);
                      travelGroupDao.setTravelgroupAndTravelitem(map);
                  }
              }
     }


}
